const http = require('http').createServer()
const io = require('socket.io')(http)
http.listen(8081)

let users = {} // id:socket
let msgQueue = {} // id:[msgdata*N]
io.on('connection', (socket) => {
  socket.on('login', (id) => {
    if (users[id] === undefined) {
      users[id] = socket
      console.log(`user:${id} is login`)
    }
    if (msgQueue[id] !== undefined) {
      users[id].emit('receiveOfflineMsg', msgQueue[id])
      console.log(`user:${id} receive offline msg`)
    }
  })
  socket.on('sendMsg', (data) => {
    users[data.from].emit('sendMsg', data)
    if (users[data.to] === undefined) {
      if (!(msgQueue[data.to] instanceof Array)) {
        msgQueue[data.to] = []
      }
      msgQueue[data.to].push(data)
      console.log(`id:${data.to} push a msg: ${data.msg}`)
    } else {
      users[data.to].emit('receiveMsg', data)
    }
  })
})
